package com.example.aidlclient

import android.app.Service
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Binder
import android.os.IBinder
import android.os.RemoteCallbackList
import android.util.Log
import com.example.aidlclient.aidl.Book
import com.example.aidlclient.aidl.IBookManager
import com.example.aidlclient.aidl.IOnCountListener
import java.util.concurrent.CopyOnWriteArrayList


class BookService : Service() {

    private val mBookList = CopyOnWriteArrayList<Book>()

    private val mListeners = RemoteCallbackList<IOnCountListener>()

    private val mBinder = object : IBookManager.Stub() {
        override fun getBookList(): MutableList<Book> {
            LogUtil.e("getBookList--> " + Thread.currentThread())
            LogUtil.e("callingPid--> " + Binder.getCallingPid())
            return mBookList
        }

        override fun addBook(book: Book?) {
            LogUtil.e("addBook--> " + Thread.currentThread())
            Thread.sleep(2000)
            mBookList.add(book)
            repeat(mListeners.beginBroadcast()) {
                mListeners.getBroadcastItem(it)?.onCountChanged(mBookList.size)
            }
            mListeners.finishBroadcast()
        }

        override fun printBook() {
            LogUtil.e("printBook--> " + Thread.currentThread())
            Thread.sleep(2000)
        }

        override fun registerListener(listener: IOnCountListener?) {
            mListeners.register(listener)
            LogUtil.e("registerListener--> " + Thread.currentThread())
        }

        override fun unregisterListener(listener: IOnCountListener?) {
            mListeners.unregister(listener)
            LogUtil.e("unregisterListener--> " + Thread.currentThread())
        }
    }

    override fun onBind(intent: Intent?): IBinder? {
        val check = checkCallingOrSelfPermission("per.wsj.freedoor.permission.ACCESS_VPN_SERVICE")
        if (check == PackageManager.PERMISSION_DENIED) {
            LogUtil.e("PERMISSION_DENIED--> " + Thread.currentThread())
            return null
        }
        LogUtil.e("PERMISSION_GRANTED--> " + Thread.currentThread())
        return mBinder
    }

    override fun onCreate() {
        super.onCreate()
        LogUtil.e("onCreate--> " + Thread.currentThread())

        mBookList.add(Book(1, "Android"))
        mBookList.add(Book(2, "IOS"))
    }
}